package com.imflea.zero.service.meeting.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imflea.zero.constant.AdoptConstant;
import com.imflea.zero.constant.PayConstant;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.model.dao.meeting.MeetingOrderInfoMapper;
import com.imflea.zero.model.entity.invoice.dto.InsertWxApplayDto;
import com.imflea.zero.model.entity.meeting.MeetingOrderInfo;
import com.imflea.zero.model.entity.meeting.MeetingRoom;
import com.imflea.zero.model.entity.meeting.dto.*;
import com.imflea.zero.model.entity.meeting.vo.DateTime4ItemStatusVO;
import com.imflea.zero.model.entity.pay.PayRecorderInfo;
import com.imflea.zero.model.entity.pay.dto.PaySuccessDto;
import com.imflea.zero.model.entity.user.WebUserAccount;
import com.imflea.zero.service.invoice.IInvoiceInfoService;
import com.imflea.zero.service.meeting.*;
import com.imflea.zero.service.pay.IPayRecorderInfoService;
import com.imflea.zero.service.user.IWebUserAccountService;
import com.imflea.zero.util.ZeroJsonUtils;
import com.imflea.zero.util.base.CommonJsonUtils;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.utils.OrderUtils;
import com.imflea.zero.utils.SessionUtils;
import com.imflea.zero.utils.TaskTimeOutUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单主表 服务实现类
 * </p>
 *
 * @author xiangbaoyu
 * @since 2021-09-24
 */
@Service
@Slf4j
public class MeetingOrderInfoServiceImpl extends ServiceImpl<MeetingOrderInfoMapper, MeetingOrderInfo> implements IMeetingOrderInfoService {

    @Autowired
    @Lazy
    private IInvoiceInfoService invoiceInfoService;
    @Autowired
    private IMeetingRoomService meetingRoomService;
    @Autowired
    private IMeetingCouponRuleService meetingCouponRuleService;
    @Autowired
    private IWebUserAccountService webUserAccountService;
    @Autowired
    private IPayRecorderInfoService payRecorderInfoService;
    @Autowired
    private IMeetingOrderInfoItemService meetingOrderInfoItemService;
    @Autowired
    private IMeetingShopUserService meetingShopUserService;


    @Override
    public MeetingOrderInfo saveOrUpdateRechargeInfo(RechargeOrderAppSaveDto dto) {

        BigDecimal totalAmount = dto.getPreTotalAmount();
        MeetingOrderInfo order = new MeetingOrderInfo();
        order.setPayAmount(dto.getPreTotalAmount());
        order.setOrderType("2");//充值订单
        order.setOrderSn(OrderUtils.generateOrderSn());
        order.setOrderStatus(0);
        order.setId(CommonUtils.generateRandomString());
        order.setMemberId(SessionUtils.getUserId());
        order.setMemberName(SessionUtils.getWxNickName());
        order.setTotalAmount(totalAmount);

        // 计算赠送规则

        BigDecimal semAmount = meetingCouponRuleService.getSemAmount(dto.getPreTotalAmount());
        order.setSemAmount(semAmount);
        return this.saveOrUpdateMeetingOrderInfo(order);
    }

    @Override
    public MeetingOrderInfo saveOrUpdateMeetingOrderInfo(MeetingOrderInfo entity) {
        if (CommonUtils.isNull(entity.getId())) {
            entity.setId(CommonUtils.generateRandomString());
        }
        LocalDateTime now = LocalDateTime.now();
        entity.setTenantId(SessionUtils.getTenantId());
        entity.setCommitTime(now);
        this.saveOrUpdate(entity);
        return entity;
    }


    public static List<LocalDate> getDatesBetween(LocalDateTime startTime, LocalDateTime endTime) {

        int startHour = startTime.getHour();
        int endHour = endTime.getHour();
        int firstFlag = 0;
        List<LocalDate> dates = new ArrayList<>();
        //这里是判断开始日期是否在结束日期之后或者=结束日期
        while (startTime.isBefore(endTime) || startTime.isEqual(endTime)) {
            dates.add(startTime.toLocalDate());
            boolean isSameDay = startTime.toLocalDate().isEqual(endTime.toLocalDate());
            int calHour = 24;
            if (isSameDay) {
                calHour = endHour;
            }
            int start = 0;
            if (firstFlag == 0) {
                start = startHour;
            }
            for (int i = start; i <= calHour; i++) {
                System.out.println(startTime.toLocalDate() + "------" + i + ":00");
            }

            startTime = startTime.plusDays(1);
        }
        System.out.println(startHour);
        System.out.println(endHour);
        return dates;
    }

    public static void main(String[] args) {
        //        2024-03-01：1：00
//        2024-04-01：3：00
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd:HH");
        LocalDateTime startTime = LocalDateTime.parse("2024-03-01:10", timeFormatter);
        LocalDateTime endTime = LocalDateTime.parse("2024-03-01:10", timeFormatter);
        List<LocalDate> dates = getDatesBetween(startTime, endTime);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        boolean isSameDay = startTime.toLocalDate().compareTo(endTime.toLocalDate()) == 0;
//        int startHour = startTime.getHour();
//        int endHour = endTime.getHour();
//        System.out.println(startHour);
//        System.out.println(endHour);
//        for (LocalDate date : dates) {
//
//            System.out.println(date.format(formatter));
//        }
    }

    @Override
    public MeetingOrderInfo saveOrUpdateMeetingRoomInfo(MeetingOrderAppSaveDto dto) {
        MeetingRoom room = meetingRoomService.getById(dto.getBizId());
        String shopId = room.getShopId();
        MeetingOrderInfo order = new MeetingOrderInfo();
        String nickName = SessionUtils.getWxNickName();
        LocalDateTime startTime = dto.getStartTime();
        LocalDateTime endTime = dto.getEndTime();
        Integer orderAmount = this.caculateTime(startTime, endTime);
        Float price = room.getPrice();
        BigDecimal payTotalAmount = new BigDecimal(price * orderAmount);
        BigDecimal totalAmount = payTotalAmount;
        BigDecimal preTotalAmount = null;
//        if (!payTotalAmount.equals(preTotalAmount)) {
//            throw new BizException("订单价格不符，请重新下单");
//        }
        order.setStartTime(dto.getStartTime());
        order.setEndTime(dto.getEndTime().plusMinutes(59L).plusSeconds(59L));
        order.setOrderSn(OrderUtils.generateOrderSn());
        //待支付
        order.setOrderStatus(0);
        order.setBizId(dto.getBizId());
        order.setId(CommonUtils.generateRandomString());
        order.setBizName(room.getRoomName());
        order.setMemberId(SessionUtils.getUserId());
        order.setMemberName(nickName);
        order.setOrderType("1");//空间订单
        order.setPayAmount(payTotalAmount);
        order.setAdoptAmount(orderAmount);
        order.setSingleAmount(new BigDecimal(price));
        order.setShopId(shopId);
        try {
            order.setBizJson(ZeroJsonUtils.entityToJson(room));
        } catch (Exception e) {

        }
        order.setTotalAmount(totalAmount);
//        //优惠金额
//        order.setSemAmount(regionTotal.subtract(payTotalAmount));


        //是否开票 是否开票信息，是：发票抬头信息
        String invoiceHeadId = dto.getInvoiceHeadId();
        MeetingOrderInfo result = this.saveOrUpdateMeetingOrderInfo(order);
        if (!CommonUtils.isNull(invoiceHeadId)) {
            //保存 发票申请关联信息
            InsertWxApplayDto dtos = new InsertWxApplayDto();
            dtos.setInvoiceHeaderId(invoiceHeadId);
            dtos.setOrderId(order.getId());
            dtos.setOrderSn(order.getOrderSn());
            dtos.setOrderType(PayConstant.ORDER_TYPE_MEETING_ROOM.getCode());
            invoiceInfoService.insertWxApplay(dtos);
        }
        this.meetingOrderInfoItemService.saveOrderItemByOrder(order);
        //扣库存
//        Boolean subStock = this.adoptSkuService.updateStock(adoptSku.getId(), adoptAmount);
//        if (!subStock) {
//            throw new BizException("库存扣除失败");
//        }
        //超时时间配置：
        TaskTimeOutUtil.enqueue(AdoptConstant.MEETING_ORDER_TIME_OUT_SQU.getCode(), order.getId(), Integer.valueOf(AdoptConstant.MEETING_ORDER_TIME_OUT_TIME_SECONDS.getCode()));
        return result;
    }


    @Override
    public PageInfo<MeetingOrderInfo> queryPage(MeetingOrderInfoDto dto) {
        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        String tenantId = SessionUtils.getTenantId();
        String orderSn = dto.getOrderSn();
        String memberName = dto.getMemberName();
        Integer orderStatus = dto.getOrderStatus();
        LocalDateTime commitTime = dto.getCommitTime();
        String payType = dto.getPayType();
        String orderType = dto.getOrderType();

        Boolean mdAdmin = SessionUtils.isMdAdmin();


        SessionUtils.isZbAdmin();


        QueryWrapper<MeetingOrderInfo> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        if (!CommonUtils.isNull(orderSn)) {
            queryWrapper.like("order_sn", orderSn);
        }
//        if (mdAdmin) {
//            shopIds = meetingShopUserService.queryShopIdsByUserId(SessionUtils.getUserId());
//        }

        if (!CommonUtils.isNull(memberName)) {
            queryWrapper.like("member_name", memberName);
        }

        if (!CommonUtils.isNull(orderStatus)) {
            queryWrapper.eq("order_status", orderStatus);
        }
        if (!CommonUtils.isNull(commitTime)) {
            queryWrapper.eq("commit_time", commitTime);
        }
        if (!CommonUtils.isNull(payType)) {
            queryWrapper.eq("pay_type", payType);
        }
        if (!CommonUtils.isNull(orderType)) {
            queryWrapper.eq("order_type", orderType);
        }

        if (SessionUtils.isMdAdmin()) {
            queryWrapper.eq("order_type", "1");
            List<String> shopIds = meetingShopUserService.queryShopIdsByUserId(SessionUtils.getUserId());
            if (!CommonUtils.isNull(shopIds)) {
                queryWrapper.in("shop_id", shopIds);
            }
        } else {
            if (!CommonUtils.isNull(orderType)) {
                queryWrapper.eq("order_type", orderType);
            }
        }


        queryWrapper.orderByDesc("commit_time");
        PageHelper.startPage(pageIndex, pageSize);
        List<MeetingOrderInfo> adoptInfos = this.list(queryWrapper);
        PageInfo<MeetingOrderInfo> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    @Override
    public PageInfo<MeetingOrderInfo> queryPage4App(MeetingOrderInfoDto dto) {
        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        String tenantId = SessionUtils.getTenantId();
        String memberId = SessionUtils.getUserId();
        String orderType = dto.getOrderType();

        Integer orderStatus = dto.getOrderStatus();
        LocalDateTime commitTime = dto.getCommitTime();

        QueryWrapper<MeetingOrderInfo> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }

        if (!CommonUtils.isNull(orderStatus)) {
            queryWrapper.eq("order_status", orderStatus);
        }
        if (!CommonUtils.isNull(orderType)) {
            queryWrapper.eq("order_type", orderType);
        }
        if (!CommonUtils.isNull(commitTime)) {
            queryWrapper.eq("commit_time", commitTime);
        }
        queryWrapper.eq("member_id", memberId);
        queryWrapper.orderByDesc("commit_time");
        PageHelper.startPage(pageIndex, pageSize);
        List<MeetingOrderInfo> adoptInfos = this.list(queryWrapper);
        PageInfo<MeetingOrderInfo> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    @Override
    public MeetingOrderInfo queryOrderByOrderSn(String orderSn) {
        if (CommonUtils.isNull(orderSn)) {
            return null;
        }
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("order_sn", orderSn);
        List<MeetingOrderInfo> orderInfoList = this.listByMap(columnMap);
        if (orderInfoList != null && orderInfoList.size() == 1) {
            return orderInfoList.get(0);
        }
        return null;
    }


    /**
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author 祥保玉
     * @description 统计订单销售信息
     * @date 2021/12/28  14:01
     */


    @Override
    public Map<String, Object> query4Stat(String orderType) {

        QueryWrapper<MeetingOrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
        orderInfoQueryWrapper.eq("tenant_id", SessionUtils.getTenantId());
        orderInfoQueryWrapper.eq("order_status", 3);
        //空间订单
        orderInfoQueryWrapper.eq("order_type", orderType);
        //订单总成交量
        List<MeetingOrderInfo> allFinishOrders = this.list(orderInfoQueryWrapper);
        if (CommonUtils.isNull(allFinishOrders)) {
            allFinishOrders = new ArrayList<>();
        }
        LocalDate today = LocalDate.now();
        LocalDate yesToday = today.plusDays(-1);
        List<MeetingOrderInfo> yesterdayOrders = new ArrayList<>();
        List<MeetingOrderInfo> todayOrders = new ArrayList<>();


        //昨日订单信息
        for (MeetingOrderInfo info : allFinishOrders) {
            LocalDate commitDate = info.getCommitTime().toLocalDate();
            if (commitDate.isEqual(yesToday)) {
                yesterdayOrders.add(info);
            }
            if (commitDate.isEqual(today)) {
                todayOrders.add(info);
            }

        }


        //今日订单信息
        Map<String, Object> map = new HashMap<>();

        Map<String, Integer> orderQuantity = new HashMap<>();
        orderQuantity.put("total", allFinishOrders.size());
        orderQuantity.put("today", todayOrders.size());
        orderQuantity.put("yesterday", yesterdayOrders.size());
        map.put("orderQuantity", orderQuantity);
        Map<String, BigDecimal> orderAmount = new HashMap<>();
        BigDecimal totalAmount = allFinishOrders.stream().map(MeetingOrderInfo::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal todayAmount = todayOrders.stream().map(MeetingOrderInfo::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal yesterdayAmount = yesterdayOrders.stream().map(MeetingOrderInfo::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        orderAmount.put("total", totalAmount);
        orderAmount.put("today", todayAmount);
        orderAmount.put("yesterday", yesterdayAmount);
        Map<String, List<MeetingOrderInfo>> groupByBeforeDays = new HashMap<>();
        List<Integer> orderQuantityList = new ArrayList<>();
        List<BigDecimal> orderAmountList = new ArrayList<>();
        for (int i = -14; i <= 0; i++) {
            final Integer before = i;
            LocalDate key = today.plusDays(before);
            List<MeetingOrderInfo> tempOrders = allFinishOrders.stream().filter(item -> item.getCommitTime().toLocalDate().isEqual(key)).collect(Collectors.toList());
            groupByBeforeDays.put(String.valueOf(i), tempOrders);
            orderQuantityList.add(tempOrders.size());
            BigDecimal tempAmount = tempOrders.stream().map(MeetingOrderInfo::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            orderAmountList.add(tempAmount);
        }

        map.put("orderAmount", orderAmount);
        map.put("orderQuantityList", orderQuantityList);
//        map.put("orderAmountList", orderAmountList);

        return map;
    }

    /**
     * @param orderId
     * @return java.lang.Boolean
     * @author 祥保玉
     * @description 订单超时未支付，订单取消
     * @date 2022/1/4  10:12
     */


    @Override
    public Boolean updateCancelUnpayOrder(String orderId) {
        MeetingOrderInfo orderInfo = this.getById(orderId);
        if (CommonUtils.isNull(orderInfo)) {
            throw new BizException("订单不存在");
        }
        //待付款
        Boolean isWaitPay = orderInfo.getOrderStatus().equals(0);

        if (isWaitPay) {
            return this.changeOrder2Invalid(orderId);
        }
        return false;
    }

    @Override
    public Boolean updatePayTypeByIds(List<String> orderIds, String payType) {

        UpdateWrapper<MeetingOrderInfo> queryWrapper = new UpdateWrapper<>();
        queryWrapper.in("id", orderIds);
        queryWrapper.set("pay_type", payType);
        return this.update(queryWrapper);
    }

    @Override
    public Boolean updateSemInfo(MeetingOrderInfo orderInfo) {
        if (orderInfo.getOrderType().equals("2")) {
            BigDecimal semAmout = orderInfo.getSemAmount();
            webUserAccountService.updateAountByUserId(SessionUtils.getUserId(), semAmout);
            return true;

        } else {
            return true;
        }
    }

    @Override
    public boolean updatePay2RoomOrder(String orderId) {
        MeetingOrderInfo orderInfo = this.getById(orderId);
        if (CommonUtils.isNull(orderInfo)) {
            throw new BizException("订单不存在");
        }
        Integer status = orderInfo.getOrderStatus();
        if (!"1".equals(orderInfo.getOrderType())) {
            throw new BizException("该订单不是空间订单，不能支付");
        }
        if (CommonUtils.isNull(status) || !status.equals(0)) {
            throw new BizException("该订单不是待支付状态不可支付");
        }
        BigDecimal totalAmount = orderInfo.getTotalAmount();
        if (CommonUtils.isNull(totalAmount) || totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BizException("支付金额应该大于0");
        }
        WebUserAccount userAccount = this.webUserAccountService.getAccountByUserId(SessionUtils.getUserId());
        if (CommonUtils.isNull(userAccount) || userAccount.getUserAccount().compareTo(totalAmount) < 0) {
            throw new BizException("余额不足，请及时充值");
        }
        BigDecimal account = userAccount.getUserAccount();
        BigDecimal restAccount = account.subtract(orderInfo.getTotalAmount());
        if (restAccount.compareTo(BigDecimal.ZERO) < 0) {
            throw new BizException("余额不足，请及时充值");
        }
        userAccount.setUserAccount(restAccount);
        String paySn = OrderUtils.generateOrderSn();
        this.webUserAccountService.saveOrUpdateWebUserAccount(userAccount);
        PayRecorderInfo payRecorderInfo = new PayRecorderInfo();
        //统一支付流水号
        payRecorderInfo.setPaySn(paySn);
        payRecorderInfo.setOrderType("room");
        payRecorderInfo.setOrderSn(orderInfo.getOrderSn());
        payRecorderInfo.setOrderId(orderId);
        payRecorderInfo.setPayType("Account");
        payRecorderInfo.setPayStatus("Account");
        payRecorderInfo.setTotalAmount(totalAmount);
        try {
            payRecorderInfo.setPayDetail(CommonJsonUtils.entityToJson(orderInfo));
        } catch (Exception e) {
            e.printStackTrace();
        }
        payRecorderInfo.setPayTime(LocalDateTime.now());
        payRecorderInfo.setPayUserId(SessionUtils.getUserId());
        payRecorderInfo.setPayUserName(SessionUtils.getWxNickName());
        payRecorderInfo.setPayUserOpenId(SessionUtils.getOpenId());
        orderInfo.setPaySn(paySn);
        orderInfo.setPayType("Account");
        orderInfo.setPayAmount(totalAmount);
        this.payRecorderInfoService.saveOrUpdatePayRecoderInfo(payRecorderInfo);

        this.changeOrder2Complete(orderId);


        return true;
    }

    @Override
    public List<DateTime4ItemStatusVO> getCanOrderTimeByDate(MeetingRoomDayTimeDto dayTimeDto) {
        List<DateTime4ItemStatusVO> result = meetingOrderInfoItemService.getCanOrderTimeByDateByDate(dayTimeDto);

        return result;
    }


    @Override
    public Boolean check(MeetingRoomTimeCheckDto dayTimeDto) {
        Boolean result = meetingOrderInfoItemService.check(dayTimeDto);
        return result;
    }


    @Override
    public Boolean updateWebUserAccountInfo(MeetingOrderInfo orderInfo) {

        if (!"2".equals(orderInfo.getOrderType())) {
            return true;
        }

        BigDecimal totalAmount = orderInfo.getTotalAmount();
        BigDecimal semAmount = orderInfo.getSemAmount();
        if (CommonUtils.isNull(totalAmount) || totalAmount.compareTo(BigDecimal.ZERO) <= 0) {
            return true;
        }
        WebUserAccount userAccount = this.webUserAccountService.getAccountByUserId(orderInfo.getMemberId());

        BigDecimal account = userAccount.getUserAccount();
        BigDecimal restAccount = account.add(orderInfo.getTotalAmount());
        if (!CommonUtils.isNull(semAmount)) {
            restAccount = restAccount.add(semAmount);
        }
        userAccount.setUserAccount(restAccount);
        this.webUserAccountService.saveOrUpdateWebUserAccount(userAccount);
        return true;
    }


    @Override
    public Boolean changeOrder2Confirming(String orderId) {
        return changeOrder(orderId, 1);
    }

    @Override
    public Boolean changeOrder2Confirmed(String orderId) {
        return changeOrder(orderId, 2);
    }

    @Override
    public Boolean changeOrder2Complete(String orderId) {
        return changeOrder(orderId, 3);
    }


    @Override
    public Boolean changeOrder2Complete(List<PaySuccessDto> dtos, String paySn, String payType) {

        List<String> orderIds = dtos.stream().map(item -> item.getOrderId()).collect(Collectors.toList());
        Boolean orderResult = this.changeOrder2Complete(orderIds);
        if (!orderResult) {
            throw new BizException("订单异常");
        }
        for (String orderId : orderIds) {
            TaskTimeOutUtil.dequeue(AdoptConstant.MEETING_ORDER_TIME_OUT_SQU.getCode(), orderId);
        }
        UpdateWrapper<MeetingOrderInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", orderIds);
        updateWrapper.set("pay_sn", paySn);
        updateWrapper.set("pay_type", payType);
        return this.update(updateWrapper);
    }


    @Override
    public Boolean changeOrder2Complete(List<String> orderIds) {
        List<MeetingOrderInfo> orderInfos = this.listByIds(orderIds);
        for (MeetingOrderInfo orderInfo : orderInfos) {
            if (!changeOrder(orderInfo.getId(), 3)) {
                return false;
            }
            Boolean useResult = this.updateWebUserAccountInfo(orderInfo);
            if (!useResult) {
                throw new BizException("账户余额更新失败！");
            }
            return true;
        }
        return true;
    }

    /**
     * @param orderId
     * @return java.lang.Boolean
     * @author 祥保玉
     * @description 手动关闭订单，取消订单
     * @date 2022/1/5  11:09
     */


    @Override
    public Boolean changeOrder2Cancel(String orderId) {
        MeetingOrderInfo orderInfo = this.getById(orderId);
        Integer status = orderInfo.getOrderStatus();
        if (!status.equals(0)) {
            throw new BizException("此阶段不可取消订单");
        }
        Integer amount = orderInfo.getAdoptAmount();
        //充值订单
        if ("2".equals(orderInfo.getOrderType())) {
            //无需处理
        } else if ("1".equals(orderInfo.getOrderType())) {
            //会议空间订单，需要释放时间@TODO
            Boolean result = this.meetingOrderInfoItemService.removeByOrderId(orderId);
            if (!result) {
                throw new BizException("订单取消失败！");
            }

        }
//        String skuId = orderInfo.getAdoptSku();
//        Boolean backStock = adoptSkuService.updateStock4Add(skuId, amount);
//        if (!backStock) {
//            throw new BizException("库存退还失败");
//        }
//        boolean semCheckResult = semAdoptCouponBizService.updateCouponUnLocks(orderId);
//        if (!semCheckResult) {
//            throw new BizException("认养券退还失败");
//        }
        TaskTimeOutUtil.dequeue(AdoptConstant.MEETING_ORDER_TIME_OUT_SQU.getCode(), orderId);
        return changeOrder(orderId, 4);
    }

    /**
     * @param orderId
     * @return java.lang.Boolean
     * @author 祥保玉
     * @description 定时任务调用，此时会自动消费
     * @date 2022/1/5  11:09
     */


    @Override
    public Boolean changeOrder2Invalid(String orderId) {

        MeetingOrderInfo orderInfo = this.getById(orderId);
        Integer status = orderInfo.getOrderStatus();
        if (!status.equals(0)) {
            throw new BizException("此阶段不可关闭订单");
        }
//        Boolean backStock = adoptSkuService.updateStock4Add(skuId, amount);
//        if (!backStock) {
//            throw new BizException("库存退还失败");
//        }
//        boolean semCheckResult = semAdoptCouponBizService.updateCouponUnLocks(orderId);
//        if (!semCheckResult) {
//            throw new BizException("认养券退还失败");
//        }

        return changeOrder(orderId, 5);
    }


    private Integer caculateTime(LocalDateTime startTime, LocalDateTime endTime) {
        int result = 0;
        int startHour = startTime.getHour();
        int endHour = endTime.getHour();
        int firstFlag = 0;
        List<LocalDate> dates = new ArrayList<>();
        //这里是判断开始日期是否在结束日期之后或者=结束日期
        while (startTime.isBefore(endTime) || startTime.isEqual(endTime)) {
            dates.add(startTime.toLocalDate());
            boolean isSameDay = startTime.toLocalDate().isEqual(endTime.toLocalDate());
            int calHour = 24;
            if (isSameDay) {
                calHour = endHour;
            }
            int start = 0;
            if (firstFlag == 0) {
                start = startHour;
            }
            for (int i = start; i <= calHour; i++) {
                result++;
            }

            startTime = startTime.plusDays(1);
        }
        return result;
    }


    private Boolean changeOrder(String orderId, Integer status) {
        MeetingOrderInfo orderInfo = this.getById(orderId);
        orderInfo.setOrderStatus(status);
        Boolean infoResult = this.saveOrUpdate(orderInfo);
        return infoResult;
    }


}
